const vscode = require('vscode');
const { getCodeCompletion } = require('../utils/utils.js');

let lastRequest = null;
let items = [];

// 检查当前位置是否不应提供补全
function shouldNotComplete(document, position) {
  // 检查光标是否在注释或字符串中
  const lineText = document.lineAt(position.line).text;
  
  // 检查光标是否在行末尾
  const isAtLineEnd = position.character === lineText.length;
  
  // 检查光标前一个字符是否是 }, ), ;
  if (position.character > 0) {
    const prevChar = lineText.charAt(position.character - 1);
    if (['}'].includes(prevChar)) {
      return true;
    }
  }
  
  // 检查光标之后不是空的或只有闭合符号
  let selectionTrailingString = lineText.substring(position.character);
  // 如果后面只有空格、括号、分号等，那么可以补全
  let re = /^[\s\]\}\); \n\r\t\'\"]*$/;
  return !re.test(selectionTrailingString) && !isAtLineEnd;
}

// 获取光标后面的内容
function getTextAfterCursor(document, position) {
  const currentLine = document.lineAt(position.line);
  
  // 获取当前行光标后的内容
  let textAfterCursor = currentLine.text.substring(position.character);
  
  // 获取剩余行的内容
  let remainingText = '';
  const lineCount = document.lineCount;
  const maxLinesToCheck = Math.min(50, lineCount - position.line - 1); // 最多获取50行
  
  for (let i = 1; i <= maxLinesToCheck; i++) {
    const line = document.lineAt(position.line + i);
    remainingText += '\n' + line.text;
    
    // 如果遇到函数、类结束或空行，提前停止
    if (line.text.trim() === '' || /^[\s]*\}/.test(line.text)) {
      break;
    }
  }
  
  return textAfterCursor + remainingText;
}

module.exports = function inlineCompletionProvider() {
  const provider = {
    provideInlineCompletionItems: async function(document, position, context, token) {
      if (context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke) {
        return { items: items };
      } 
      else if (context.triggerKind === vscode.InlineCompletionTriggerKind.Automatic) {
        // 判断功能是否开启
        const config = vscode.workspace.getConfiguration('qwenChat');
        const enableCompletion = config.get('codeCompletion');
        const delayConfig = config.get('completionDelay') || 0.5;
        const delay = delayConfig * 1000;
        
        if (!enableCompletion) {
          return;
        }

        const editor = vscode.window.activeTextEditor;
        if (!editor) {
          vscode.window.showInformationMessage(
            "请先打开一个文件以使用代码补全功能"
          );
          return;
        }

        // 检查当前位置是否应该提供补全
        if (shouldNotComplete(document, position)) {
          return;
        }

        // 获取光标前的文本
        const beforeSelection = new vscode.Selection(0, 0, position.line, position.character);
        let textBeforeCursor = document.getText(beforeSelection);

        // 处理换行
        if (position.character === 0 && 
            textBeforeCursor[textBeforeCursor.length - 1] !== "\n") {
          textBeforeCursor += "\n";
        }

        // 如果光标前没有内容则不补全
        if (textBeforeCursor.trim() === "") {
          return { items: [] };
        }

        // 获取光标后的文本
        const textAfterCursor = getTextAfterCursor(document, position);

        const requestId = new Date().getTime();
        lastRequest = requestId;
        await new Promise(resolve => setTimeout(resolve, delay));

        if (lastRequest !== requestId) {
          return { items: [] };
        }
        
        try {
          // 使用 AI API 获取补全结果，传递前后文
          const prompt = `${textBeforeCursor}<|fim_suffix|>${textAfterCursor}`;
          const result = await getCodeCompletion(prompt);
          items = result.map(item => {
            return new vscode.InlineCompletionItem(
              item, 
              new vscode.Range(
                position,
                position
              )
            );
          });
          
          return { items: items };
        } catch (error) {
          vscode.window.showErrorMessage(error.message);
          return { items: [] };
        }
      }
    }
  };
  
  return provider;
}
